﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using UI.Lib;
using System.Threading;
using UI.CommonForm;
using UI.Test;
using System.Data;
using UI.Lib.Factory;
using Components;
using System.IO;

namespace UI
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Control.CheckForIllegalCrossThreadCalls = false; //不限制非要创建控件的进程调用控件
            Application.EnableVisualStyles();
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
            Application.SetCompatibleTextRenderingDefault(false);
            Thread thShowText = null;

            #region 登录验证相关

            FrmLogin frm = new FrmLogin(); //登录框
            if (frm.ShowDialog() == DialogResult.OK)
            {
                frm.Hide();
                FrmLoading frmLoading = new FrmLoading();//显示等待窗口
                frmLoading.StartPosition = FormStartPosition.CenterScreen;
                frmLoading.Show();

                string guid = ""; //登录标识
                string loginGuid = "";
                string userName = frm.LoginUserName;//得到登录的用户名
                string userPwd = frm.LoginPwd;

                //得到本次登录验证票
                string stkcode = Guid.NewGuid().ToString();

                try
                {
                    thShowText = new Thread(new ThreadStart(frmLoading.SetText1)); //笨拙的显示消息的方法
                    thShowText.Name = "showText";
                    thShowText.Priority = ThreadPriority.Normal;
                    thShowText.IsBackground = true;
                    thShowText.Start();
                    thShowText.Join();

                    string tmpKey = CommonHelper.Entity.Exchange(stkcode); //得到服务器验证票
                    //LogHelper.Entity.Out("提取验证票");
                    SecurityEncryption.key = stkcode.Substring(0, 8);
                    loginGuid = SecurityEncryption.Decrypt(tmpKey); //哈哈哈，我收到服务器的验证票了
                    if (string.IsNullOrEmpty(loginGuid))
                    {
                        MessageBox.Show(new PsException(3).ErrMsg, "提示");
                        Application.Restart();
                    }

                    Context.AddGuid(loginGuid);
                }
                catch (PsException ex)
                {
                    MessageBox.Show(ex.ErrMsg, "提示");
                    Application.Restart();
                }

                SecurityEncryption.key = loginGuid;

                thShowText = new Thread(new ThreadStart(frmLoading.SetText2)); //笨拙的显示消息的方法
                thShowText.Name = "showText";
                thShowText.Priority = ThreadPriority.Normal;
                thShowText.IsBackground = true;
                thShowText.Start();
                thShowText.Join();

                string encryptName = SecurityEncryption.Encrypt(userName);
                string fileName = string.Concat(Context.ApplicationPath, "\\", userName);
                bool isExitsFile = File.Exists(fileName);
                string rereulst = CommonHelper.Entity.Login(encryptName,
                    SecurityEncryption.Encrypt(userPwd), stkcode, isExitsFile); //验证登录
                //LogHelper.Entity.Out("登录");
                if (string.IsNullOrEmpty(rereulst))
                {
                    MessageBox.Show(new PsException(1).ErrMsg, "提示");
                    Context.RemoveLoginKey();
                    Application.Restart();
                    return;
                }

                string[] rsts = rereulst.Split('|');
                if ("S1" == rsts[0])
                {
                    guid = rsts[1];
                }
                else
                {
                    MessageBox.Show(rsts[1], "提示");
                    Context.RemoveLoginKey();
                    Application.Restart();
                    return;
                }

                Context.AddUser(guid, userName); //保存用户标识, 由于下面的查询会自动加上Guid,所以在查询操作之前，必须要把AddUser放成全局的变量

                FrmMain mainfm = new FrmMain(userName, guid); //实例化Main窗口

                mainfm.StateChange += new FrmMain.State(frmLoading.SetPlan);//如果加载的状态改变时，同时现在是loading窗口上

                Thread thUI = new Thread(new ThreadStart(mainfm.LoadMenuContext));
                thUI.Name = "Loading";
                thUI.Priority = ThreadPriority.Highest;
                thUI.IsBackground = true;
                thUI.Start();

                thUI.Join();//等到显示Loading窗口的进程结束之后，才打开主页面

                if (!string.IsNullOrEmpty(frmLoading.Msg))
                {
                    frmLoading.SetErrorMsg();
                    Thread.Sleep(1000 * 3); //停顿3秒 结束
                    CommonHelper.Entity.LoginOut(guid);
                    Application.Restart();
                }
                else
                {
                    frmLoading.Hide();
                    if (!isExitsFile) //创建登录标识
                    {
                        CommonUtil.GetInstance.SaveToFile(fileName, "");
                        File.SetAttributes(fileName, FileAttributes.Hidden);
                    }
                    Application.Run(mainfm);
                }
            }
            #endregion
        }

        static void Application_ApplicationExit(object sender, EventArgs e)
        {
            if ("auto" == Validation.ToString(Context.GetValueByKey("exit")))
            {
                Context.RemoveCache("exit");
                Application.Restart();
            }
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            LogHelper.Entity.Out("错误来源：" + e.Exception + "；其他信息：" + e.Exception.ToString());
            MessageBox.Show((new PsException(0)).ErrMsg, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            ////遇到未处理的异常不提示任何信息
            LogHelper.Entity.Out("错误来源：" + e.ExceptionObject + "；其他信息：" + e.ToString());
            MessageBox.Show((new PsException(0)).ErrMsg, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
